package com.comprehensive.personalmovie.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.comprehensive.common.dto.MovieCmsPamas;
import com.comprehensive.common.enumType.DataSourceEnum;
import com.comprehensive.common.po.Dictionary;
import com.comprehensive.common.po.Movies;
import com.comprehensive.personalmovie.feign.DictionaryFeignClient;
import com.comprehensive.personalmovie.service.MovieService;
import com.comprehensive.personalmovie.service.VideoCrawlerService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class VideoCrawlerServiceImpl implements VideoCrawlerService {

    private final String DIST_CODE="YSCMS";
    @Autowired
    private MovieService movieService;
    @Autowired
    private DictionaryFeignClient dictionaryFeignClient;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public List<Movies> crawlMovie(MovieCmsPamas movieCmsPamas) {
        List<Dictionary> dictionaries = dictionaryFeignClient.queryDictionariesByTypeOrCode(DIST_CODE, null);
        if (Objects.isNull(dictionaries) || dictionaries.isEmpty()) {
            return new ArrayList<>();
        }
        List<Movies>result=new ArrayList<>();
        for (Dictionary dictionary : dictionaries) {
            String dictValue = dictionary.getDictValue();
            JSONObject jsonObject = JSONUtil.parseObj(dictValue);
            String url = jsonObject.getStr("url");
            if (StringUtils.isBlank(url)) {
                continue;
            }
            if (StringUtils.isNotBlank(movieCmsPamas.getIds())) {
                result.addAll(buildRequestCms(url,null,null,null,null,movieCmsPamas.getIds()));
                continue;
            }
            if (StringUtils.isNotBlank(movieCmsPamas.getWd())) {
                result.addAll(buildRequestCms(url,movieCmsPamas.getWd(),null,movieCmsPamas.getPageNum(),movieCmsPamas.getHours(),null));
                continue;
            }
            String types=null;
            if (ObjectUtils.isNotEmpty(movieCmsPamas.getType())) {
                types=jsonObject.getStr(movieCmsPamas.getType().getCode());
            }
            if (StringUtils.isNotBlank(types)) {
                for (String type : types.split(",")) {
                    result.addAll(buildRequestCms(url,null,type,movieCmsPamas.getPageNum(),movieCmsPamas.getHours(),movieCmsPamas.getIds()));
                }
            }
            result.addAll(buildRequestCms(url,null,null,movieCmsPamas.getPageNum(),movieCmsPamas.getHours(),null));
        }
        return result;
    }
    @Override
    public Object crawlMovieDetail(MovieCmsPamas movieCmsPamas) throws JsonProcessingException {
        List<Dictionary> dictionaries = dictionaryFeignClient.queryDictionariesByTypeOrCode(DIST_CODE, null);
        if (Objects.isNull(dictionaries) || dictionaries.isEmpty()) {
            return new ArrayList<>();
        }
        for (Dictionary dictionary : dictionaries) {
            String dictValue = dictionary.getDictValue();
            JSONObject jsonObject = JSONUtil.parseObj(dictValue);
            String url = jsonObject.getStr("url");
            if (StringUtils.isBlank(url)) {
                continue;
            }
            if (StringUtils.isNotBlank(movieCmsPamas.getIds())) {
                StringBuilder urlBuilder = new StringBuilder(url);
                urlBuilder.append("?ac=").append("detail");
                urlBuilder.append("&ids=").append(movieCmsPamas.getIds());
                url = urlBuilder.toString();

                String response = restTemplate.getForObject(url, String.class);
                JsonNode rootNode = objectMapper.readTree(response);
                int code = rootNode.path("code").asInt();

                if (code != 1) {

                    return new ArrayList<>();
                }

                JsonNode listNode = rootNode.path("list");
                if (!listNode.isArray()) {

                    return null;
                }

                return listNode.get(0);
            }
        }
        return null;
    }

    @Override
    public int saveCrawledMovies(List<Movies> movies) {
        if (movies == null || movies.isEmpty()) {
            return 0;
        }

        int successCount = 0;
        for (Movies movie : movies) {
            try {
                // 检查电影是否已存在
                Movies existingMovie = movieService.getMovieById(movie.getId());
                if (existingMovie == null) {
                    // 新增电影
                    boolean saved = movieService.addMovie(movie);
                    if (saved) {
                        successCount++;
                    }
                } else {
                    // 更新电影
                    movie.setId(existingMovie.getId());
                    boolean updated = movieService.updateMovie(movie);
                    if (updated) {
                        successCount++;
                    }
                }
            } catch (Exception e) {

            }
        }


        return successCount;
    }

    private List<Movies> buildRequestCms(String url,String wd,String typeId,String pageNum,String hours,String ids) {
        StringBuilder urlBuilder = new StringBuilder(url);
        urlBuilder.append("?ac=").append("detail");
        if (StringUtils.isNotBlank(wd)) {
            urlBuilder.append("&wd=").append(wd);
        }

        if (Objects.nonNull(ids)) {
            urlBuilder.append("&ids=").append(ids);
        }
        if (Objects.nonNull(typeId)) {
            urlBuilder.append("&t=").append(typeId);
        }
        if (Objects.nonNull(pageNum)) {
            urlBuilder.append("&pg=").append(pageNum);
        }
        if (Objects.nonNull(hours)) {
            urlBuilder.append("&h=").append(hours);
        }

        url = urlBuilder.toString();


        try {

            String response = restTemplate.getForObject(url, String.class);
            return parseMovieListResponse(response);
        } catch (Exception e) {

            return new ArrayList<>();
        }
    }

    /**
     * 解析电影列表响应数据
     */
    private List<Movies> parseMovieListResponse(String response) throws IOException {
        JsonNode rootNode = objectMapper.readTree(response);
        int code = rootNode.path("code").asInt();

        if (code != 1) {

            return new ArrayList<>();
        }

        JsonNode listNode = rootNode.path("list");
        if (!listNode.isArray()) {

            return new ArrayList<>();
        }

        List<Movies> movies = new ArrayList<>();
        for (JsonNode itemNode : listNode) {
            Movies movie = new Movies();
            movie.setSourceMovieId(itemNode.path("vod_id").asLong());
            movie.setTitle(itemNode.path("vod_name").asText());
            movie.setType(0);
            movie.setSource(DataSourceEnum.CMS_COLLECTION.getValue());
            if (StringUtils.isNotBlank(itemNode.path("vod_class").asText())) {
                movie.setGenre(itemNode.path("vod_class").asText());
            }
            if (StringUtils.isNotBlank(itemNode.path("vod_douban_score").asText())) {
                movie.setRating(itemNode.path("vod_douban_score").asText());
            }
            if (StringUtils.isNotBlank(itemNode.path("vod_time").asText())) {
                movie.setReleaseDate(LocalDateTimeUtil.parse(itemNode.path("vod_time").asText(),"yyyy-MM-dd HH:mm:ss").toLocalDate());
            }
            // 解析详情字段（如果有）
            if (itemNode.has("vod_pic")) {
                movie.setPosterUrl(itemNode.path("vod_pic").asText());
            }
            if (itemNode.has("vod_area")) {
                movie.setCountry(itemNode.path("vod_area").asText());
            }
            if (itemNode.has("vod_actor")) {
                movie.setActors(itemNode.path("vod_actor").asText());
            }
            if (itemNode.has("vod_director")) {
                movie.setDirector(itemNode.path("vod_director").asText());
            }
            if (itemNode.has("vod_content")) {
                movie.setDescription(itemNode.path("vod_content").asText());
            }

            movies.add(movie);
        }

        return movies;
    }
}